package org.bulu.project.web.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bulu.project.common.result.Result;
import org.bulu.project.system.model.entity.SysUser;
import org.bulu.project.system.model.form.UserForm;
import org.bulu.project.system.security.SecurityUtils;
import org.bulu.project.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

//个人消息主页相关操作
@RestController
@RequestMapping("/api/v1/palcenter")
@RequiredArgsConstructor
@Slf4j
public class PalController {

    private  String uploadUrl ;

    @Autowired
    private SysUserService sysUserService;

    //查询个人相关消息
    @GetMapping("/find")
    public Result selectById() {
        Long id =  SecurityUtils.getUserId();
        return Result.success(sysUserService.getById(id));
    }


    //修改个人相关消息
    @PostMapping("/update")
    public Result updateById(@RequestBody SysUser sysUser ) throws IOException {
        return Result.success(sysUserService.updateUser(sysUser.getId(),sysUser));
    }

    //修改头像
    @PostMapping("upload")
    public String uploadHead(MultipartFile file){
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString().replaceAll("-","") + suffix ;
        File f = new File(uploadUrl,filename);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return filename;
    }
}
